<script lang="tsx">
import { defineComponent, ref } from 'vue';
import { ElButton, ElMessage } from 'element-plus';
import { $t } from '@vben/locales';
import { getSubjectTreeListApi, createSubjectCategoryApi, updateSubjectCategoryApi, delSubjectCategoryApi } from '#/api/manage/subject';
import { usePage } from '#/hooks/page/usePage';
import { Pencil, Trash2 } from '@vben/icons';
import subOrgIcon from '#/assets/images/sub-add.png';
import deleteIcon from '#/assets/images/delete-icon.png';
import EditDialog from './modules/subject-mgr/edit-dialog.vue';

export default defineComponent({
  name: 'SubjectCategoryPage',
  setup() {
    // 弹窗相关状态
    const showDialog = ref(false);
    const dialogMode = ref<'add' | 'edit'>('add');
    const dialogFormData = ref<any>({}); // 弹窗表单数据
    const parentOptions = ref<any[]>([]); // 弹窗父级科目下拉选项
    const loading = ref(false) // 弹窗确定按钮loading

    // 表格列配置
    const columns = [
      { type: 'selection', width: 50, align: 'center', prop: '' },
      { prop: 'name', label: $t('subject.subjectName'), minWidth: 250, showOverflowTooltip: true },
      { prop: 'createTime', label: $t('subject.addTime'), minWidth: 150, showOverflowTooltip: true },
    ];

    // 查询区配置
    const queryColumns = [
      { prop: 'name', label: $t('subject.subjectName'), type: 'input', placeholder: $t('common.inputPhTxt') },
      {
        prop: 'createTime',
        label: $t('subject.addTime'),
        type: 'daterange',
        component: 'el-date-picker',
        rangeSeparator: $t('common.rangeSeparatorTxt'),
        unlinkPanels: true,
        startPlaceholder: $t('common.startTimeTxt'),
        endPlaceholder: $t('common.endTimeTxt'),
        format: "YYYY-MM-DD",
        'value-format': "YYYY-MM-DD HH:mm:ss",
        'default-time': [
          new Date(2000, 1, 1, 0, 0, 0),
          new Date(2000, 1, 1, 23, 59, 59),
        ],
        style: { minWidth: '230px' },
        // 添加change事件处理
        onChange: (val: any) => {
          changeDateRange(val);
        }
      },
    ];

    // API配置
    const API = {
      get: getSubjectTreeListApi,
      delete: delSubjectCategoryApi,
    };

    // 操作按钮配置
    const commands = [
      {
        key: 'post',
        width: 40,
        render: (row: any, index?: number) => {
          return (
            <el-tooltip
              effect="dark"
              content={$t('subject.addSonSubject')}
              show-after={600}
              placement="top"
            >
              <el-button
                link
                onClick={() => { handleAdd(); dialogFormData.value.pid = row.id; }}
              ><el-icon style={{
                backgroundImage: `url(${subOrgIcon})`,
                backgroundSize: '100% 100%',
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'center'
              }}></el-icon> </el-button>
            </el-tooltip>
          );
        },
      },
      {
        key: 'put',
        width: 40,
        icon: Pencil,
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={ $t('common.editTxt', [''])}
            show-after={600}
            placement="top"
          >
            <el-button link onClick={() => handleEdit(row)}><el-icon><Pencil /></el-icon></el-button>
          </el-tooltip>
        ),
      },
      {
        key: 'delete',
        width: 40,
        label: $t('common.deleteTxt', ['']),
        icon: Trash2,
      },
    ];

    const deleteProps = {
      title: $t(''),
      message: `
        <div style="display: flex; align-items: center;">
          <img src="${deleteIcon}" style="width: 48px; height: 48px; margin-right: 10px;" />
          <span>${$t('subject.deleteMessageTip')}</span>
        </div>
      `,
      confirmButtonText: $t('common.confirm'),
      cancelButtonText: $t('common.cancel'),
      customClass: 'delete-dialog',
      dangerouslyUseHTMLString: true,
      center: false,
    };

    // 使用页面表格hooks
    const {
      render,
      getTableData,
      queryState,
      tableState
    } = usePage({
      API,
      columns,
      queryColumns,
      commands,
      deleteProps,
    });

    // 表格树结构设置
    tableState['row-key'] = 'id'
    tableState['tree-props'] = { children: 'children' }

    // 获取父级科目下拉选项 -- 每次弹窗出现都要获取最新的下拉筛选
    const fetchParentOptions = async (id?: string) => {
      const res = await getSubjectTreeListApi({});
      // 转换为 el-tree-select 需要的格式
      const convert = (list = []) => {
        return list.map((item: any) => {
          const convertedItem: any = {
            label: item.name,
            value: item.id
          };
          // 先处理子节点
          if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            convertedItem.children = convert(item.children);
          }
          // 处理禁用逻辑-不能选择自己
          if (item.id === id) convertedItem.disabled = true;
          return convertedItem;
        });
      };
      parentOptions.value = convert(res.data || []);
    };

    // 添加时间选择器事件处理
    const changeDateRange = (val: any) => {
      if (val && val.length === 2) {
        // 手动将值拆分到startTime和endTime
        queryState.data.startTime = val[0]
        queryState.data.endTime = val[1]
      } else {
        queryState.data.startTime = ''
        queryState.data.endTime = ''
      }
    };
    // 新增按钮事件
    const handleAdd = () => {
      dialogMode.value = 'add';
      dialogFormData.value = { name: '', pid: '' };
      showDialog.value = true;
      fetchParentOptions();
    };
    // 编辑按钮事件
    const handleEdit = (row: any) => {
      dialogMode.value = 'edit';
      dialogFormData.value = { ...row };
      showDialog.value = true;
      fetchParentOptions(row.id);
    };

    // 弹窗点击确认
    const handleDialogConfirm = async (formData: any) => {
      loading.value = true;
      if (dialogMode.value === 'add') {
        await createSubjectCategoryApi(formData).then(() => {
          ElMessage.success($t('common.newTxt', [$t('common.successTxt')]))
        }).finally(() => {
          loading.value = false;
        })
      } else {
        await updateSubjectCategoryApi(formData).then(() => {
          ElMessage.success($t('common.editTxt', [$t('common.successTxt')]))
        }).finally(() => {
          loading.value = false;
        })
      }
      showDialog.value = false;
      getTableData();
    };
    // 弹窗点击取消
    const handleDialogCancel = () => {
      showDialog.value = false;
      dialogFormData.value = {};
    };

    return () => (
      <div>
        {render({
          header: (
            <ElButton type="primary" onClick={handleAdd}>
              {$t('common.newTxt')}
            </ElButton>
          ),
          table: {
            prefix: () => [] // 覆盖默认的 prefix，不包含 serialColumn
          }
        })}
        <EditDialog
          modelValue={showDialog.value}
          formData={dialogFormData.value}
          mode={dialogMode.value}
          loadFlag={loading.value}
          parentTreeOptions={parentOptions.value}
          onUpdate:modelValue={val => showDialog.value = val}
          onConfirm={handleDialogConfirm}
          onCancel={handleDialogCancel}
        />
      </div>

    );
  }
});
</script>
